package com.project.light.filter;

import com.alibaba.fastjson.JSON;
import com.project.light.entity.System;
import com.project.light.service.LoginService;
import com.project.light.util.RestResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Calendar;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!request.getRequestURI().contains("DoLogin")) {
            String token = request.getHeader("authorization");
            if (StringUtils.isEmpty(token)) {
                response.setContentType("text/json; charset=utf-8");
                RestResult result = RestResult.error("请求头部未包含token");
                PrintWriter writer = response.getWriter();
                writer.print(JSON.toJSON(result));
                return false;
            } else {
                if (!request.getRequestURI().contains("post")) {
                    // 验证token有效性
                    System entity = loginService.getByToken(token);
                    if (entity == null) {
                        response.setContentType("text/json; charset=utf-8");
                        RestResult result = RestResult.error("token不正确");
                        PrintWriter writer = response.getWriter();
                        writer.print(JSON.toJSON(result));
                        return false;
                    } else {
                        Calendar calendar = Calendar.getInstance();
                        long now = calendar.getTime().getTime();
                        if (now > entity.getExpirationDate().getTime()) {
                            response.setContentType("text/json; charset=utf-8");
                            RestResult result = RestResult.error("token已过期,请重新登录");
                            PrintWriter writer = response.getWriter();
                            writer.print(JSON.toJSON(result));
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
